using UnityEngine;
using Mirror;
using TMPro;
public class Player : NetworkBehaviour //MonoBehaviour --> NetworkBehaviour
{
    public GameObject camera;
    public TMP_Text nameText;//名字
    public GameObject bomb;//炸弹预制体
    private Animator anim; // 动画组件
    private ChatController chatController;
    //速度：每秒移动5个单位长度
    public float moveSpeed = 5;

    //需要把name和颜色同步给其他玩家，添加同步变量的标记[SyncVar(hook=nameof(FunctionExecOnClient))]
    [SyncVar(hook = nameof(OnPlayerNameChanged))]
    public string playerName;
    [SyncVar(hook = nameof(OnPlayerColorChanged))]
    private Color playerColor;
    private Rigidbody2D rb; // 刚体组件
    //申明OnPlayerNameChanged和OnPlayerColorChanged这两个方法
    //第一个变量(oldstr)是同步变量修改前的值，第二个(newstr)是同步变量修改后的值
    private void OnPlayerNameChanged(string oldstr, string newstr)
    {
        nameText.text = newstr;
    }
    private void OnPlayerColorChanged(Color oldCor, Color newCor)
    {
        nameText.color = newCor;
    }
    void Awake()
    {
        chatController = FindObjectOfType<ChatController>();
        camera = GameObject.Find("Main Camera");
    }
    public override void OnStartLocalPlayer()
    {
        //摄像机与角色绑定
        camera.transform.SetParent(transform);
        camera.transform.localPosition = new Vector3(0, 0, camera.transform.position.z);

        //随机生成颜色和名字
        ChangedColorAndName();

        rb = GetComponent<Rigidbody2D>(); // 获取刚体组件
        anim = gameObject.GetComponentInChildren<Animator>(); // 获取动画组件


        chatController.player = this;
    }

    [Command]
    public void CmdSendPLayerMessage(string message)
    {
        Debug.Log(333);
        if (chatController != null)
        {
            chatController.chatTextString = playerName + "说:" + message;
        }
    }

    // 角色是否死亡的标志
    [SyncVar(hook = nameof(OnIsDeadChanged))]
    public bool isDead = false;

    // 当角色死亡状态改变时的回调方法
    void OnIsDeadChanged(bool oldValue, bool newValue)
    {
        if (newValue)
        {
            // 执行死亡逻辑，例如播放死亡动画、禁用角色控制等
            Debug.Log("Player has died.");
            Destroy(gameObject, 2f); // 延迟2秒后销毁角色对象
        }
    }

    void Update()
    {
        if (!isLocalPlayer) return; //不应操作非本地玩家

        Move();

        if (Input.GetKeyDown(KeyCode.Space))
        {
            //随机生成颜色和名字
            ChangedColorAndName();
        }
        //攻击动画
        if (Input.GetMouseButtonDown(0))
        {
            anim.SetTrigger("isAttack");
            anim.SetBool("isIdle", false);
        }
        else
        {
            anim.SetBool("isIdle", true);
        }
        //生成炸弹
        if (Input.GetMouseButtonDown(1))
        {
            Cmdshoot();
        }
        if (Input.GetKeyDown(KeyCode.T))
        {
            
            CmdDestroyPlayerServer();

            // 创建一个新的Camera对象
            GameObject cameraObject = new GameObject("Main Camera");
            // 添加Camera组件到对象上
            Camera cameraComponent = cameraObject.AddComponent<Camera>();
            // 设置摄像机的位置和旋转
            cameraComponent.transform.position = new Vector3(0, 0, -10f);
            cameraComponent.transform.rotation = Quaternion.identity;
        }

    }

    //服务端销毁角色
    [Command]
    private void CmdDestroyPlayerServer()
    {
        isDead = true;
    }

    [Command]
    private void Cmdshoot()
    {
        //同步方法一
        GameObject b = Instantiate(bomb, transform.position, Quaternion.identity);
        b.transform.Translate(1, 0, 0);//防止子弹撞到角色
        b.GetComponent<Rigidbody2D>().AddForce(Vector2.up * 500f);
        Destroy(b, 2.0f);//两秒后删除
        NetworkServer.Spawn(b);//服务器孵化，同步客户端
        //同步方法二
        // RpcWeaponFire();
    }

    [ClientRpc]
    private void RpcWeaponFire()
    {
        GameObject b = Instantiate(bomb, transform.position, Quaternion.identity);
        b.GetComponent<Rigidbody2D>().AddForce(Vector2.up * 500f);
    }


    void Move()
    {
        //通过键盘获取水平轴的值，范围在-1到1
        float horizontal = Input.GetAxisRaw("Horizontal");
        rb.velocity = new Vector2(horizontal * moveSpeed, rb.velocity.y); // 设置刚体速度
        if (horizontal != 0)
        {
            transform.GetChild(0).localScale = new Vector3(-horizontal, 1, 1); // 翻转角色
        }
    }


    //player 的随机名称和颜色
    private void ChangedColorAndName()
    {
        //随机名称和颜色
        var tempName = $"Player{Random.Range(1, 999)}";
        var tempColor = new Color(Random.Range(0, 1f), Random.Range(0, 1f), Random.Range(0, 1f), 1);

        //同步变量进行修改
        CmdSetupPlayer(tempName, tempColor);
    }

    //对于同步变量的修改，使用[Command]标记(针对方法的标记，方法名以Cmd开头)
    //通过这个方法同时对name和颜色进行修改
    [Command]
    private void CmdSetupPlayer(string name, Color color)
    {
        playerName = name;
        playerColor = color;
    }
}